part of 'index.dart';

class ConversationProvider extends ChangeNotifier {
  List<EMConversation> conversations = [];
  StreamSubscription<List<EMMessage>>? _messageSubscription;
  // ignore: unused_field
  StreamSubscription? _conversationStream;
  int retry = 0;
  NoticeCountModel? countModel;
  bool _disposed = false;

  ConversationProvider() {
    _fetchCount();
    loadConversations();
    _messageSubscription = ImManager.of.messageStream.listen((event) {
      loadConversations();
    });
    _conversationStream = ImManager.of.conversationStream.listen((event) {
      loadConversations();
    });
  }

  void _fetchCount() async {
    countModel = await ImAPI.noticeCount();
    if (!_disposed) notifyListeners();
  }

  loadConversations() async {
    if (_disposed) return;
    conversations = await ImManager.of.loadAllConversations();
    if (conversations.isEmpty) {
      conversations = await ImManager.of.fetchConversations();
    }
    if (!_disposed) notifyListeners();

    if (conversations.isEmpty) {
      Future.delayed(const Duration(milliseconds: 500), () {
        if (_disposed) return;
        if (conversations.isNotEmpty) return;
        if (retry < 3) {
          retry++;
          loadConversations();
        }
      });
    }
    if (conversations.isNotEmpty) {
      final ids = conversations.map((e) => e.id).join(',');
      ImAPI.getImStatus(ids).then((value) {
        if (value.isEmpty) return;
        ImManager.of.onlineUsers.addAll(value);
      });
    }
  }

  // 删除会话
  deleteConversation(String? conversationId) async {
    conversations.removeWhere((e) => e.id == conversationId);
    if (!_disposed) notifyListeners();
    ImManager.of.deleteConversation(conversationId);
  }

  //
  jumpToChat(EMConversation conversation, chat.UserInfo? user) {
    Get.to(() => ChatPage(conversation: conversation, user: user))
        ?.then((value) {
      if (!_disposed) loadConversations();
    });
    ImManager.of.clearUnread(conversation.id).then((value) {
      if (!_disposed) loadConversations();
    });
  }

  clearUnread(String? conversationId) {
    ImManager.of.clearUnread(conversationId).then((value) {
      if (!_disposed) loadConversations();
    });
  }

  jumpToCustomer() {
    final conversation = EMConversation.fromJson({
      'convId': ImManager.customerId,
      'type': 0,
    });
    final user = chat.UserInfo.fromJson({
      'userId': ImManager.customerId,
      'nickName': T.current.c_custom_service,
    });
    clearNoticeUnread('CUSTOMER_ADMIN');
    Get.to(() => ChatPage(conversation: conversation, user: user))
        ?.then((value) => loadConversations());
  }

  jumpToSystemNotice() {
    final conversation = EMConversation.fromJson({
      'convId': ImManager.systemNoticeId,
      'type': 0,
    });
    clearNoticeUnread('NOTICE_ADMIN');
    Get.to(() => SystemNotificationPage(conversation));
  }

  jumpToPlatformNotice() {
    final conversation = EMConversation.fromJson({
      'convId': ImManager.platformNoticeId,
      'type': 0,
    });
    clearNoticeUnread('PROCLAMATION_ADMIN');
    Get.to(() => PlatformNotificationPage(conversation));
  }

  void clearNoticeUnread(String fromImId) async {
    switch (fromImId) {
      case 'NOTICE_ADMIN': // 系统通知
        countModel?.NOTICE_ADMIN = 0;
        break;
      case 'PROCLAMATION_ADMIN': // 平台通知
        countModel?.PROCLAMATION_ADMIN = 0;
        break;
      case 'CUSTOMER_ADMIN': // 客服通知
        countModel?.CUSTOMER_ADMIN = 0;
        break;
    }
    if (!_disposed) notifyListeners();
    await ImAPI.clearNoticeCount(fromImId);
  }

  @override
  void dispose() {
    _disposed = true;
    _messageSubscription?.cancel();
    _conversationStream?.cancel();
    super.dispose();
  }
}
